﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Threading;
using System.Net.Sockets;
using System.Net;
using System.Collections;
using System.Windows;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
//using Microsoft.Win32;

namespace PCclient2._0
{
    public partial class Form1 : Form
    {
        public const int SHOW = 1;
        public const int COPYTOANDROID = 2;
        public const int PASTEFROMANDROID = 3;
        public const int OTHERFILES = 4;
        public const int CUT = 5;
        public const int RENAME = 6;
        public const int ADNROIDTOANDROID = 7;
        public const int DELETE = 8;
        public const int NEW = 9;
        public const int CONNECT = 10;
        public const int SHOWOTHERDIR = 11;
        public const int SHOWOTHERFILE = 12;
        public const int STOP = 20;

        public const int EVERYGETCOUNTS = 15;

        /**按修改时间，降序*/
        public const int TYPE_MODIFIED_DATE_DOWN = 1;
        /**按修改时间，升序*/
        public const int TYPE_MODIFIED_DATE_UP = 2;
        /**按文件大小，降序*/
        public const int TYPE_SIZE_DOWN = 3;
        /**按文件大小，升序*/
        public const int TYPE_SIZE_UP = 4;
        /**按文件名*/
        public const int TYPE_NAME = 5;
        /**按目录，文件排序*/
        public const int TYPE_DIR  = 7;

        public const string CONFIG_IP = "remember";
        public const string CONFIG_WIDTH = "width";
        public const string CONFIG_HEIGHT = "height";
        public const string CONFIG_REMEMBER_FLAG = "reFlag";
        public const string CONFIG_VIEW = "view";
        public const string CONFIG_COLUMN_NAME_WIDTH = "columnNameWidth";
        public const string CONFIG_COLUMN_TIME_WIDTH = "columnTimeWidth";
        public const string CONFIG_COLUMN_SIZE_WIDTH = "columnSizeWidth";

        private int arrangeType = TYPE_NAME;

        private List<string> copyFileInPC;
        private List<string> copyDirInPC;
        private List<string> filePaths;
        private List<string> fileNames;
        private List<string> filePathsForAndroid;
        private List<string> copyInAndroid;
        private List<string> deleteList;
        private string pastePCPath;
        private string renamePath;
        private string renameDestPath;

        private string clickName;

        private bool copyingFlag = false;
        private bool cutFlag = false;
        private bool alertFlag = false;
        private bool isRename;
        private bool timeOutFlag = false;
        private bool openFlag = false;
        private bool isLoadingFlag = false;
        private bool showIPWrongAlert = false;
        private bool isConnectFlag;

        private int splitButtonIndex = 0;
        private int sendCmd = 1;
        private Thread sendThread;

        private int menuIndex = 0;
        private string threadMenuName = "SD卡";
        private string threadPath = "";

        private copying copyForm = null;
        private loading loadingForm = null;

        private ListViewItem renameItem;
        private XMLOperation xmlOperation;

        private string host = "";
        private IPEndPoint ipe;

        //private CreateLogFiles Err;

        public Form1()
        {
            //Err = new CreateLogFiles();

            InitializeComponent();
            xmlOperation = new XMLOperation();
            initFormSize();
            initPCToolStrip();

            copyFileInPC = new List<string>();
            copyDirInPC = new List<string>();
            copyInAndroid = new List<string>();
            filePaths = new List<string>();
            fileNames = new List<string>();
            filePathsForAndroid = new List<string>();
            deleteList = new List<string>();
            initTextBox();

            this.大图标ToolStripMenuItem.Click += new System.EventHandler(this.图标ToolStripMenuItem_Click);
            this.详细列表ToolStripMenuItem.Click += new System.EventHandler(this.详细ToolStripMenuItem_Click);

            排列方式ToolStripMenuItem.Visible = false;

            string listViewView = xmlOperation.readConfig(CONFIG_VIEW,"");
            if (listViewView == "Details")
            {
                listViewForAndroid.View = View.Details;
                listViewForPC.View = View.Details;
            }
        }

        private void initFormSize()
        {
            int width = Int32.Parse(xmlOperation.readConfig(CONFIG_WIDTH, "730"));
            int height = Int32.Parse(xmlOperation.readConfig(CONFIG_HEIGHT, "500"));
            this.ClientSize = new System.Drawing.Size(width, height);
        }

        private void initTextBox()
        {
            
            //xmlOperation.write("10.0.0.9");
            textBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
            textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
            //textBox1.AutoCompleteCustomSource.AddRange(new string[] { "10.0.0", "10.0.08", "5.0.0", "85" }); 

            AutoCompleteStringCollection acsc = new AutoCompleteStringCollection();
            //acsc.Add("asdjhkj");
            //acsc.Add("2412312");
            //acsc.Add("asdaasdkj");
            //acsc.Add("78fsdfhj");
            List<string> strList = xmlOperation.readIP();
            foreach (string ips in strList)
            {
                acsc.Add(ips);
            }
            if (xmlOperation.readConfig(CONFIG_REMEMBER_FLAG, "false")=="true")
            {
                checkBox1.Checked = true;
                textBox1.Text = xmlOperation.readConfig(CONFIG_IP, "");
            }
            textBox1.AutoCompleteCustomSource = acsc;
        }

        private void cleanStringList()
        {
            copyFileInPC.Clear();
            copyDirInPC.Clear();
            copyInAndroid.Clear();
            filePaths.Clear();
            fileNames.Clear();
            filePathsForAndroid.Clear();
        }



        private void initPCToolStrip()
        {
            ToolStripSplitButton PCRootSplitButton = new ToolStripSplitButton();
            PCRootSplitButton.Text = "计算机";
            PCRootSplitButton.ButtonClick += new EventHandler(PCRootSplitButton_ButtonClick);
            PCRootSplitButton.DropDownItemClicked += new ToolStripItemClickedEventHandler(PCRootSplitButton_DropDownItemClicked);
            this.toolStripForPC.Items.Add(PCRootSplitButton);
            initPCListView(PCRootSplitButton);
        }

        void PCRootSplitButton_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            splitButtonIndex = 0;
            for (int i = toolStripForPC.Items.Count - 1; i > 0; i--)
            {
                toolStripForPC.Items.RemoveAt(i);
            }
            showPCListView(e.ClickedItem.Tag.ToString(), e.ClickedItem.Text, true);
        }

        void PCRootSplitButton_ButtonClick(object sender, EventArgs e)
        {

            toolStripForPC.Items.Clear();
            splitButtonIndex = 0;
            initPCToolStrip();

        }

        private void initPCListView(ToolStripSplitButton PCRootSplitButton)
        {
            initColumnHeader(this.listViewForPC);
            listViewForPC.Items.Clear();
            listViewForPC.BeginUpdate();
            DriveInfo[] drivers = DriveInfo.GetDrives();
            foreach (DriveInfo driver in drivers)
            {
                if (driver.DriveType.ToString() == "Fixed")
                {
                    ListViewItem lvi = new ListViewItem(new string[]{
                        driver.Name,"",""}, 0);
                    lvi.Tag = driver.Name.Substring(0,2);
                    listViewForPC.Items.Add(lvi);
                    ToolStripMenuItem tsmi = new ToolStripMenuItem();
                    tsmi.Text = driver.Name;
                    tsmi.Tag = driver.Name.Substring(0, 2);
                    PCRootSplitButton.DropDownItems.Add(tsmi);
                }

            }
            //RegistryKey folders;
            //folders = OpenRegistryPath(Registry.CurrentUser, @"/software/microsoft/windows/currentversion/explorer/shell folders");

            // Windows用户桌面路径

            //string desktopPath = folders.GetValue("Desktop").ToString();

            string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); 


            //MessageBox.Show(desktopPath);
            ListViewItem lviDesktop = new ListViewItem(new string[]{"桌面","",""},3);
            lviDesktop.Tag = desktopPath;
            listViewForPC.Items.Add(lviDesktop);

            listViewForPC.EndUpdate();
        }

        private void initColumnHeader(ListView lv)
        {
            lv.Columns.Clear();
            ColumnHeader colHead;
            //first header
            colHead = new ColumnHeader();
            colHead.Text = "文件名";
            colHead.Width = Int32.Parse(xmlOperation.readConfig(CONFIG_COLUMN_NAME_WIDTH,"130"));
            lv.Columns.Add(colHead);
            //second header
            colHead = new ColumnHeader();
            colHead.Text = "修改时间";
            colHead.Width = Int32.Parse(xmlOperation.readConfig(CONFIG_COLUMN_TIME_WIDTH, "150"));
            lv.Columns.Add(colHead);
            //third header
            colHead = new ColumnHeader();
            colHead.Text = "大小";
            colHead.Width = Int32.Parse(xmlOperation.readConfig(CONFIG_COLUMN_SIZE_WIDTH, "70"));
            colHead.TextAlign = HorizontalAlignment.Right;
            lv.Columns.Add(colHead);
        }

        //private void addSplitButton(string text, string path)
        //{
        //    ToolStripSplitButton PCSplitButton = new ToolStripSplitButton();
        //    PCSplitButton.Text = text;
        //    splitButtonIndex++;
        //    string tag = splitButtonIndex.ToString() + "?" + path;
        //    PCSplitButton.Tag = tag;
        //    PCSplitButton.ButtonClick += new System.EventHandler(this.PCSplitButton_ButtonClick);
        //    PCSplitButton.DropDownItemClicked += new ToolStripItemClickedEventHandler(this.PCSplitButton_DropDownItemClicked); 
        //    this.toolStripForPC.Items.Add(PCSplitButton);

        //    DirectoryInfo folder = new DirectoryInfo(path);
        //    DirectoryInfo[] subFolders = null;
        //    try
        //    {
        //        subFolders = folder.GetDirectories();
        //    }
        //    catch (UnauthorizedAccessException)
        //    {
        //        MessageBox.Show("没权限~");
        //    }
        //    if (subFolders != null)
        //    {
        //        foreach (DirectoryInfo subFolder in subFolders)
        //        {
        //            ToolStripMenuItem tsmi = new ToolStripMenuItem();
        //            tsmi.Text = subFolder.Name;
        //            tsmi.Tag = subFolder.FullName;
        //            //tsmi.
        //            PCSplitButton.DropDownItems.Add(tsmi);
        //        }
        //    }
        //}

        private void PCSplitButton_ButtonClick(object sender, EventArgs e)
        {
            ToolStripSplitButton clickedButton = sender as ToolStripSplitButton;
            string tag = clickedButton.Tag.ToString();
            String[] splitStrings = new String[2];
            char[] separator = { '?' };
            splitStrings = tag.Split(separator);
            //MessageBox.Show(splitStrings[1]);
            showPCListView(splitStrings[1], null, false);
            int currentIndex = int.Parse(splitStrings[0]);
            splitButtonIndex = currentIndex;
            for (int i = toolStripForPC.Items.Count - 1; i > currentIndex; i--)
            {
                toolStripForPC.Items.RemoveAt(i);
            }
        }


        private void showPCListView(string path, string text, bool isUpdateToolStrip)
        {
            ToolStripSplitButton PCSplitButton = null;
            if (isUpdateToolStrip)
            {
                PCSplitButton = new ToolStripSplitButton();
                PCSplitButton.Text = text;
                splitButtonIndex++;
                string tag = splitButtonIndex.ToString() + "?" + path;
                PCSplitButton.Tag = tag;

                //Err.ErrorLog("./Logs/Log.txt", "PCSplitButton--->" + tag);

                PCSplitButton.ButtonClick += new System.EventHandler(this.PCSplitButton_ButtonClick);
                PCSplitButton.DropDownItemClicked += new ToolStripItemClickedEventHandler(PCSplitButton_DropDownItemClicked);
                this.toolStripForPC.Items.Add(PCSplitButton);
            }
            listViewForPC.Items.Clear();
            this.listViewForPC.BeginUpdate();
            DirectoryInfo folder = new DirectoryInfo(path);
            //添加文件夹
            DirectoryInfo[] subFolders = null;
            try
            {
                subFolders = folder.GetDirectories();
            }
            catch (UnauthorizedAccessException)
            {
                MessageBox.Show("没权限~");
            }
            if (subFolders != null)
            {
                foreach (DirectoryInfo subFolder in subFolders)
                {
                    if (!subFolder.Attributes.ToString().Contains("System"))
                    {
                        ListViewItem lvi = new ListViewItem(new string[]{
                    subFolder.Name,subFolder.LastWriteTime.ToString(), ""}, 1);
                        lvi.Tag = subFolder.FullName;
                        listViewForPC.Items.Add(lvi);
                        if (isUpdateToolStrip)
                        {
                            ToolStripMenuItem tsmi = new ToolStripMenuItem();
                            tsmi.Text = subFolder.Name;
                            tsmi.Tag = subFolder.FullName;
                            PCSplitButton.DropDownItems.Add(tsmi);
                        }
                    }

                }
            }

            SHFILEINFO shinfo = new SHFILEINFO();

            //添加文件
            FileInfo[] files = null;
            try
            {
                files = folder.GetFiles();
            }
            catch (UnauthorizedAccessException)
            {
            }
            if (files != null)
            {
                foreach (FileInfo file in files)
                {


                    Win32.SHGetFileInfo(file.FullName, 0, ref shinfo, (uint)Marshal.SizeOf(shinfo), Win32.SHGFI_ICON | Win32.SHGFI_LARGEICON);
                    Icon fileHIcon = Icon.FromHandle(shinfo.hIcon);
                    Win32.SHGetFileInfo(file.FullName, 0, ref shinfo, (uint)Marshal.SizeOf(shinfo), Win32.SHGFI_ICON | Win32.SHGFI_SMALLICON);
                    Icon fileLIcon = Icon.FromHandle(shinfo.hIcon);
                    //ListViewItem lviFile = new ListViewItem(new string[]{
                    //file.Name,"文件",GetFileSize(file),file.LastWriteTime.ToString()});
                    ListViewItem lviFile = new ListViewItem();


                    lviFile.Text = file.Name;
                    lviFile.SubItems.Add(file.LastWriteTime.ToString());
                    lviFile.SubItems.Add(GetFileSize(file));

                    imageListPC.Images.Add(file.Name, fileLIcon);
                    imageListPCBig.Images.Add(file.Name, fileHIcon);
                    lviFile.ImageKey = file.Name;

                    lviFile.Tag = file.FullName;
                    listViewForPC.Items.Add(lviFile);
                }
            }

            this.listViewForPC.EndUpdate();
        }

        void PCSplitButton_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            ToolStripSplitButton clickedButton = sender as ToolStripSplitButton;
            string tag = clickedButton.Tag.ToString();
            String[] splitStrings = new String[2];
            char[] separator = { '?' };
            splitStrings = tag.Split(separator);
            //MessageBox.Show(splitStrings[1]);
            int currentIndex = int.Parse(splitStrings[0]);
            splitButtonIndex = currentIndex;
            for (int i = toolStripForPC.Items.Count - 1; i > currentIndex; i--)
            {
                toolStripForPC.Items.RemoveAt(i);
            }
            showPCListView(e.ClickedItem.Tag.ToString(), e.ClickedItem.Text, true);
        }

        private string GetFileSize(FileInfo file)
        {
            string result = "";
            long fileSize = file.Length;
            if (fileSize >= 1024 * 1024 * 1024)
            {
                result = string.Format("{0:#########0.00} GB", ((double)fileSize) / (1024 * 1024 * 1024));
            }
            else if (fileSize >= 1024 * 1024)
            {
                result = string.Format("{0:###0.00} MB", ((double)fileSize) / (1024 * 1024));
            }
            else if (fileSize >= 1024)
            {
                result = string.Format("{0:###0.00} KB", ((double)fileSize) / (1024));
            }
            else
            {
                result = string.Format("{0} Bytes", fileSize);
            }
            return result;
        }

        private void listViewForPC_ItemActivate(object sender, EventArgs e)
        {

            if (listViewForPC.FocusedItem.Tag != null)
            {
                string path = listViewForPC.FocusedItem.Tag.ToString();
                if (listViewForPC.FocusedItem.ImageIndex != 0 && listViewForPC.FocusedItem.ImageIndex != 1 &&listViewForPC.FocusedItem.ImageIndex != 3)
                {
                    try
                    {
                        System.Diagnostics.Process.Start(path);
                    }
                    catch
                    {
                    }
                }
                else
                {
                    //addSplitButton(listViewForPC.FocusedItem.Text, path);
                    showPCListView(path, listViewForPC.FocusedItem.Text, true);
                }
            }
        }

        //左边的ListView

        private void initAndroidListView()
        {


            initColumnHeader(this.listViewForAndroid);
            int port = 10112;
            IPAddress ip = IPAddress.Parse(host);
            ipe = new IPEndPoint(ip, port);//把ip和端口转化为IPEndPoint实例
            sendThread = new Thread(new ThreadStart(sendMess));
            sendCmd = CONNECT;
            sendThread.IsBackground = true;
            sendThread.Start();
        }

        private void sendMess()
        {


            //while (true)
            //{

                //Console.WriteLine("Conneting...");

                //string sendStr = "hel~ 中文";
                //byte[] bs = Encoding.ASCII.GetBytes(sendStr);
                //byte[] bs = Encoding.UTF8.GetBytes(sendStr);
                //Console.WriteLine("SendMessage");
                //int sendint = 1005;
                //Err.ErrorLog("./Logs/Log.txt", "isLoadingFlag  before switch--->" + this.sendThread.ThreadState.ToString());
                //if (!isLoadingFlag)
                //{
                    switch (sendCmd)
                    {
                        case SHOW:
                            isLoadingFlag = true;
                            isConnectFlag = false;
                            getFileList(ipe, threadMenuName, threadPath);
                            isLoadingFlag = false;
                            break;
                        case CONNECT:
                            isLoadingFlag = true;
                            isConnectFlag = true;
                            getFileList(ipe, threadMenuName, threadPath);

                            isLoadingFlag = false;
                            break;
                        case COPYTOANDROID:
                            isLoadingFlag = true;
                            for (int i = 0; i < fileNames.Count; i++)
                            {
                                sendFile(ipe, filePaths[i], fileNames[i], filePathsForAndroid[i]);
                            }

                            if (cutFlag)
                            {
                                MessageBox.Show("文件复制完毕,不过惊传输出错又删佐源文件就扑街啦  所以没有讲电脑端文件删除..先检查手机的文件能用不.");
                            }
                            showCopyForm(null, 0, true, false);
                            setRefreshPath();
                            getFileList(ipe, threadMenuName, threadPath);
                            copyingFlag = false;
                            isLoadingFlag = false;
                            break;
                        case PASTEFROMANDROID:
                            isLoadingFlag = true;
                            foreach (string androidPath in copyInAndroid)
                            {
                                receiveFile(ipe, androidPath, pastePCPath);
                                //Err.ErrorLog("./Logs/Log.txt", "copyInAndroid :::" + androidPath);
                            }
                            if (cutFlag)
                            {
                                MessageBox.Show("文件复制完毕,不过惊传输出错又删佐源文件就扑街啦  所以没有讲电脑端文件删除..先检查电脑的文件能用不.");

                            }
                            copyingFlag = false;
                            showCopyForm(null, 0, true, true);
                            if (openFlag)
                            {
                                //System.Diagnostics.Process.Start(".//" + clickName);

                                System.Diagnostics.Process.Start(".\\temp\\" + clickName);
                                openFlag = false;
                            }

                            isLoadingFlag = false;
                            break;
                        case RENAME:
                            isLoadingFlag = true;
                            renameInAndroid(ipe);
                            isLoadingFlag = false;
                            break;
                        case ADNROIDTOANDROID:
                            isLoadingFlag = true;
                            foreach (string root in copyInAndroid)
                            {
                                string name = root.Substring(root.LastIndexOf("/"));
                                androidForAndroid(ipe, root, name);
                                //Err.ErrorLog("./Logs/Log.txt", "copyInAndroid :::" + androidPath);
                            }
                            //showCopyForm(null, 0, true, false);
                            
                            MethodInvoker mi = new MethodInvoker(closeLoading);
                            BeginInvoke(mi);
                            setRefreshPath();
                            getFileList(ipe, threadMenuName, threadPath);
                            isLoadingFlag = false;
                            break;
                        case DELETE:
                            isLoadingFlag = true;
                            foreach (string deletePath in deleteList)
                            {
                                deleteInAndroid(ipe, deletePath);
                            }
                            showCopyForm(null, 0, true, false);
                            setRefreshPath();
                            getFileList(ipe, threadMenuName, threadPath);
                            isLoadingFlag = false;
                            break;
                        case NEW:
                            isLoadingFlag = true;
                            newDirInAndroid(ipe, renamePath);
                            isLoadingFlag = false;
                            break;
                        case STOP:
                            sendThread.Abort();
                            break;
                    }

                //}
               
                //sendThread.Suspend();
                //Err.ErrorLog("./Logs/Log.txt", "isLoadingFlag  before suspend--->" + this.sendThread.ThreadState.ToString());

            //}

        }

        private void getFileList(IPEndPoint ipe, string menuName, string path)
        {

            //Socket c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个Socket]
            TcpClient tp = null;
            NetworkStream ns = null;
            List<string> directoryNames = new List<string>();
            List<string> directoryTimes = new List<string>();
            List<string> fileNames = new List<string>();
            List<string> fileTimes = new List<string>();
            List<string> fileSizes = new List<string>();
            int directoryCount = 0;
            int fileCount = 0;

            try
            {
                tp = TimeOutSocket.Connect(ipe, 5000);//连接到服务器
                ns = tp.GetStream();

                if (path == "")
                {
                    ns.Write(Instruction2bytes(SHOW, 0, arrangeType, 0), 0, 16);
                }
                else
                {
                    byte[] pathByte = Encoding.UTF8.GetBytes(path);

                    ns.Write(Instruction2bytes(SHOW, pathByte.Length, arrangeType, 0), 0, 16);
                    ns.Write(pathByte, 0, pathByte.Length);
                }

                //获得文件夹个数,文件个数
                byte[] recvBytes = new byte[4];
                int bytes;
                bytes = ns.Read(recvBytes, 0, 4);
                int recvInt = Bytes2Int(recvBytes);
                directoryCount = recvInt;

                ns.Read(recvBytes, 0, 4);
                fileCount = Bytes2Int(recvBytes);


                int forCount = EVERYGETCOUNTS;
                if (directoryCount < EVERYGETCOUNTS)
                {
                    forCount = directoryCount;
                }
                for (int i = 0; i < forCount; i++)
                {
                    directoryNames.Add(ReceiveStringStream(ns));
                    directoryTimes.Add(ReceiveStringStream(ns));
                    //Err.ErrorLog("./Logs/Log.txt", directoryNames[i] + ":::" + directoryTimes[i]);
                }

            }
            catch (TimeoutException)
            {
                timeOutFlag = true;
                //MessageBox.Show("TimeoutException");
                if (isConnectFlag)
                {
                    MethodInvoker mi = new MethodInvoker(closeLoading);
                    BeginInvoke(mi);
                }
                dealException("连接超时");

            }
            catch (ArgumentNullException)
            {
                //Console.WriteLine("ArgumentNullException:{0}", e);
                //MessageBox.Show("ArgumentNullException");

            }
            catch (SocketException ex)
            {
                timeOutFlag = true;
                //MessageBox.Show("SocketException");
                if (isConnectFlag)
                {
                    MethodInvoker mi = new MethodInvoker(closeLoading);
                    BeginInvoke(mi);
                }
                dealException(ex.Message.ToString());

            }
            finally
            {
                if (tp != null)
                {
                    tp.Close();
                    tp = null;
                }
                if (ns != null)
                {
                    ns.Close();
                    ns = null;
                }
            }

            if (!timeOutFlag)
            {
                bool getListFlag = true;
                int times = 1;
                while (getListFlag)
                {
                    try
                    {
                        tp = TimeOutSocket.Connect(ipe, 10000);//连接到服务器
                        ns = tp.GetStream();

                        int forCounts = EVERYGETCOUNTS;
                        if ((times + 1) * EVERYGETCOUNTS > directoryCount)
                        {
                            ns.Write(Instruction2bytes(SHOWOTHERDIR, times, 1, 0), 0, 16);
                            forCounts = directoryCount - times * EVERYGETCOUNTS;
                            getListFlag = false;
                        }
                        else
                        {
                            ns.Write(Instruction2bytes(SHOWOTHERDIR, times, 0, 0), 0, 16);

                        }
                        for (int i = 0; i < forCounts; i++)
                        {
                            directoryNames.Add(ReceiveStringStream(ns));
                            directoryTimes.Add(ReceiveStringStream(ns));
                            //Err.ErrorLog("./Logs/Log.txt", directoryNames[i] + ":::" + directoryTimes[i]);
                        }
                        times++;
                    }
                    catch (TimeoutException)
                    {
                        timeOutFlag = true;
                        MessageBox.Show("TimeoutException2");
                    }
                    catch (SocketException)
                    {
                        timeOutFlag = true;
                        MessageBox.Show("SocketException2");

                    }
                    finally
                    {
                        if (tp != null)
                        {
                            tp.Close();
                            tp = null;
                        }
                        if (ns != null)
                        {
                            ns.Close();
                            ns = null;
                        }
                    }
                }

                if (fileCount != 0)
                {
                    bool getListFileFlag = true;
                    int timesFile = 0;
                    while (getListFileFlag)
                    {
                        try
                        {
                            tp = TimeOutSocket.Connect(ipe, 10000);//连接到服务器
                            ns = tp.GetStream();

                            int forFileCounts = EVERYGETCOUNTS;
                            if ((timesFile + 1) * EVERYGETCOUNTS > fileCount)
                            {
                                ns.Write(Instruction2bytes(SHOWOTHERFILE, timesFile, 1, 0), 0, 16);
                                forFileCounts = fileCount - timesFile * EVERYGETCOUNTS;
                                getListFileFlag = false;
                            }
                            else
                            {
                                ns.Write(Instruction2bytes(SHOWOTHERFILE, timesFile, 0, 0), 0, 16);

                            }
                            for (int i = 0; i < forFileCounts; i++)
                            {
                                fileNames.Add(ReceiveStringStream(ns));
                                fileTimes.Add(ReceiveStringStream(ns));
                                fileSizes.Add(ReceiveStringStream(ns));
                                //Err.ErrorLog("./Logs/Log.txt", directoryNames[i] + ":::" + directoryTimes[i]);
                            }
                            timesFile++;
                        }
                        catch (TimeoutException)
                        {
                            timeOutFlag = true;
                            MessageBox.Show("TimeoutException2");
                        }
                        catch (SocketException)
                        {
                            timeOutFlag = true;
                            MessageBox.Show("SocketException2");

                        }
                        finally
                        {
                            if (tp != null)
                            {
                                tp.Close();
                                tp = null;
                            }
                            if (ns != null)
                            {
                                ns.Close();
                                ns = null;
                            }
                        }
                    }
                }
            }


            if (isConnectFlag)
            {
                MethodInvoker mi = new MethodInvoker(closeLoading);
                BeginInvoke(mi);
            }

            showAndroidListView(menuName, directoryNames, directoryTimes, fileNames, fileTimes, fileSizes);
            //showAndroidListView(menuName, directoryNames, directoryTimes, null, null, null);

        }

        //private void getFileList(IPEndPoint ipe, string menuName, string path)
        //{

        //    //Socket c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个Socket]
        //    TcpClient tp = null;
        //    NetworkStream ns = null;
        //    try
        //    {
        //        tp = TimeOutSocket.Connect(ipe, 5000);//连接到服务器
        //        ns = tp.GetStream();

        //        if (path == "")
        //        {
        //            ns.Write(Instruction2bytes(SHOW, 0, 0, 0), 0, 16);
        //        }
        //        else
        //        {
        //            byte[] pathByte = Encoding.UTF8.GetBytes(path);

        //            ns.Write(Instruction2bytes(SHOW, pathByte.Length, 0, 0), 0, 16);
        //            ns.Write(pathByte, 0, pathByte.Length);
        //        }

        //        //获得文件夹个数,文件个数
        //        byte[] recvBytes = new byte[4];
        //        int bytes;
        //        bytes = ns.Read(recvBytes, 0, 4);
        //        int recvInt = Bytes2Int(recvBytes);
        //        int directoryCount = recvInt;

        //        ns.Read(recvBytes, 0, 4);
        //        int fileCount = Bytes2Int(recvBytes);


        //        List<string> directoryNames = new List<string>();
        //        List<string> directoryTimes = new List<string>();
        //        for (int i = 0; i < directoryCount; i++)
        //        {
        //            directoryNames.Add(ReceiveStringStream(ns));
        //            directoryTimes.Add(ReceiveStringStream(ns));
        //            //Err.ErrorLog("./Logs/Log.txt", directoryNames[i] + ":::" + directoryTimes[i]);
        //        }

        //        List<string> fileNames = new List<string>();
        //        List<string> fileTimes = new List<string>();
        //        List<string> fileSizes = new List<string>();
        //        for (int i = 0; i < fileCount; i++)
        //        {
        //            fileNames.Add(ReceiveStringStream(ns));
        //            fileTimes.Add(ReceiveStringStream(ns));
        //            fileSizes.Add(ReceiveStringStream(ns));
        //            //Err.ErrorLog("./Logs/Log.txt", fileNames[i] + ":::" + fileTimes[i] + "::::" + fileSizes[i]);
        //        }

        //        showAndroidListView(menuName, directoryNames, directoryTimes, fileNames, fileTimes, fileSizes);




        //    }
        //    catch (TimeoutException)
        //    {
        //        timeOutFlag = true;

        //    }
        //    catch (ArgumentNullException)
        //    {
        //        //Console.WriteLine("ArgumentNullException:{0}", e);

        //    }
        //    catch (SocketException)
        //    {
        //        timeOutFlag = true;
        //    }
        //    catch (Exception e)
        //    {
        //        MessageBox.Show(e.Message.ToString());
        //    }
        //    finally
        //    {
        //        if (tp != null)
        //        {
        //            tp.Close();
        //            tp = null;
        //        }
        //        if (ns != null)
        //        {
        //            ns.Close();
        //            ns = null;
        //        }
        //    }
        //}


        //private void getFileList(IPEndPoint ipe, string menuName, string path)
        //{
        //    Socket c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个Socket
        //    try
        //    {

        //        c.Connect(ipe);//连接到服务器

        //        if (path == "")
        //        {
        //            c.Send(Instruction2bytes(SHOW, 0, 0, 0), 16, 0);//发送测试信息
        //        }
        //        else
        //        {
        //            byte[] pathByte = Encoding.UTF8.GetBytes(path);
        //            c.Send(Instruction2bytes(SHOW, pathByte.Length, 0, 0), 16, 0);
        //            c.Send(pathByte);
        //        }

        //        //获得文件夹个数,文件个数
        //        byte[] recvBytes = new byte[4];
        //        int bytes;
        //        bytes = c.Receive(recvBytes, 4, 0);
        //        int recvInt = Bytes2Int(recvBytes);
        //        int directoryCount = recvInt;
        //        c.Receive(recvBytes, 4, 0);
        //        int fileCount = Bytes2Int(recvBytes);


        //        string[] directoryNames = new string[directoryCount];
        //        string[] directoryTimes = new string[directoryCount];
        //        for (int i = 0; i < directoryCount; i++)
        //        {
        //            directoryNames[i] = ReceiveString(c);
        //            directoryTimes[i] = ReceiveString(c);
        //            //Err.ErrorLog("./Logs/Log.txt", directoryNames[i] + ":::" + directoryTimes[i]);
        //        }

        //        string[] fileNames = new string[fileCount];
        //        string[] fileTimes = new string[fileCount];
        //        string[] fileSizes = new string[fileCount];
        //        for (int i = 0; i < fileCount; i++)
        //        {
        //            fileNames[i] = ReceiveString(c);
        //            fileTimes[i] = ReceiveString(c);
        //            fileSizes[i] = ReceiveString(c);
        //            //Err.ErrorLog("./Logs/Log.txt", fileNames[i] + ":::" + fileTimes[i] + "::::" + fileSizes[i]);
        //        }

        //        showAndroidListView(menuName, directoryNames, directoryTimes, fileNames, fileTimes, fileSizes);

        //    }
        //    catch (ArgumentNullException)
        //    {
        //        //Console.WriteLine("ArgumentNullException:{0}", e);

        //    }
        //    catch (SocketException)
        //    {
        //        //Console.WriteLine("SocketException:{0}", e);
        //        MessageBox.Show("SocketException");
        //    }
        //    catch (Exception e)
        //    {
        //        MessageBox.Show(e.Message.ToString());
        //    }
        //    finally
        //    {
        //        if (c != null)
        //        {
        //            c.Close();
        //            c = null;
        //        }
        //    } 
        //}

        private void sendFile(IPEndPoint ipe, string path, string name, string androidPath)
        {
            TcpClient tp = null;
            NetworkStream ns = null;
            try
            {

                //c.Connect(ipe);//连接到服务器

                tp = TimeOutSocket.Connect(ipe, 5000);//连接到服务器
                ns = tp.GetStream();

                using (FileStream fsSource = new FileStream(path, FileMode.Open, FileAccess.Read))
                {

                    byte[] pathByte = Encoding.UTF8.GetBytes(androidPath);
                    byte[] nameByte = Encoding.UTF8.GetBytes(name);
                    ns.Write(Instruction2bytes(COPYTOANDROID, pathByte.Length, nameByte.Length, (int)fsSource.Length), 0, 16);
                    ns.Write(pathByte, 0, pathByte.Length);
                    ns.Write(nameByte, 0, nameByte.Length);
                    //Err.ErrorLog("./Logs/Log.txt", "copy path--->" + path + "copy name--->" + name);

                    byte[] bytes = new byte[10 * 1024];

                    long numBytesToRead = fsSource.Length;
                    //long twoG = 1024 * 1024 * 1024 * 2;
                    int totalSize = 0;

                    totalSize = (int)numBytesToRead;
                    int everyPath = totalSize / 100;
                    int numBytesRead = 0;

                    int count = 0;
                    int mCount = 0;

                    while (numBytesToRead > 0)
                    {
                        // Read may return anything from 0 to numBytesToRead.
                        int n = fsSource.Read(bytes, 0, bytes.Length);

                        if (n == 0)
                            break;
                        //fsNew.Write(bytes, 0, n);
                        ns.Write(bytes, 0, n);

                        //if (count % 512 == 0)
                        //{
                        //    showCopyForm(name, 5 * mCount, false, false);
                        //    mCount++;
                        //}
                        //count++;

                        numBytesRead += n;
                        numBytesToRead -= n;

                        count = numBytesRead / everyPath;
                        if (count > mCount)
                        {
                            mCount = count;
                            showCopyForm(name, mCount, false, false);
                        }
                    }

                    //byte[] recvBytes = new byte[4];
                    //c.Receive(recvBytes, 4, 0);
                    //int result = Bytes2Int(recvBytes);
                    //MessageBox.Show(result.ToString());

                }

            }
            catch (TimeoutException)
            {
                timeOutFlag = true;
                //MessageBox.Show("TimeoutException");
                dealException("连接超时");

            }
            catch (ArgumentNullException)
            {
                //Console.WriteLine("ArgumentNullException:{0}", e);

            }
            catch (SocketException ex)
            {
                //Console.WriteLine("SocketException:{0}", e);
                dealException(ex.Message.ToString());
            }
            catch (Exception e)
            {
                dealException(e.Message.ToString());
            }
            finally
            {
                if (tp != null)
                {
                    tp.Close();
                    tp = null;
                }
                if (ns != null)
                {
                    ns.Close();
                    ns = null;
                }
            }
        }

        private void receiveFile(IPEndPoint ipe, string androidPath, string pcPath)
        {
            int counts = 0;
            int filesCount = 0;
            bool flag = true;
            while (true)
            {
                Socket c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个Socket
                try
                {

                    c.Connect(ipe);//连接到服务器

                    if (flag)
                    {
                        byte[] pathByte = Encoding.UTF8.GetBytes(androidPath);

                        //if (cutFlag)
                        //{
                        //    c.Send(Instruction2bytes(PASTEFROMANDROID, pathByte.Length, 0, 0), 16, 0);
                        //}

                        c.Send(Instruction2bytes(PASTEFROMANDROID, pathByte.Length, 0, 0), 16, 0);


                        c.Send(pathByte);

                        byte[] filesBytes = new byte[4];
                        c.Receive(filesBytes, 4, 0);
                        filesCount = Bytes2Int(filesBytes);
                        flag = false;
                        //Err.ErrorLog("./Logs/Log.txt", "filesCount --->" + filesCount);
                    }
                    else
                    {
                        c.Send(Instruction2bytes(OTHERFILES, 0, 0, 0), 16, 0);
                    }

                    string path = pcPath + ReceiveString(c);

                    string name = ReceiveString(c);
                    if (openFlag)
                    {
                        clickName = name;
                    }

                    //Err.ErrorLog("./Logs/Log.txt", "pcPath --->" + path + "      file name--->" + name);
                    //获得文件大小
                    byte[] recvBytes = new byte[4];
                    c.Receive(recvBytes, 4, 0);
                    int size = Bytes2Int(recvBytes);
                    //Err.ErrorLog("./Logs/Log.txt", "file size--->" + size.ToString());
                    //新建文件
                    Directory.CreateDirectory(path);
                    using (FileStream fsNew = new FileStream(path + "\\" + name, FileMode.Create, FileAccess.Write))
                    {
                        byte[] bytes = new byte[10 * 1024];

                        long numBytesToRead = size;
                        int numBytesRead = 0;


                        int totalSize = 0;
                        totalSize = (int)numBytesToRead;
                        int everyPath = totalSize / 100;
                        int count = 0;
                        int mCount = 0;

                        while (numBytesToRead > 0)
                        {
                            // Read may return anything from 0 to numBytesToRead.
                            int n = c.Receive(bytes, bytes.Length, 0);

                            if (n == 0)
                                break;
                            fsNew.Write(bytes, 0, n);


                            //if (count % 512 == 0)
                            //{
                            //    showCopyForm(name, 5 * mCount, false, true);
                            //    mCount++;
                            //}
                            //count++;

                            numBytesRead += n;
                            numBytesToRead -= n;
                            count = numBytesRead / everyPath;
                            if (count > mCount)
                            {
                                mCount = count;
                                showCopyForm(name, mCount, false, false);
                            }
                        }
                    }

                    counts++;
                    if (counts == filesCount)
                    {
                        break;
                    }


                }
                catch (ArgumentNullException)
                {
                    //Console.WriteLine("ArgumentNullException:{0}", e);

                }
                catch (SocketException ex)
                {
                    //Console.WriteLine("SocketException:{0}", e);
                    dealException(ex.Message.ToString());
                }
                catch (Exception ex)
                {
                    dealException(ex.Message.ToString());
                }
                finally
                {
                    if (c != null)
                    {
                        c.Close();
                        c = null;
                    }

                }
            }

        }

        private void renameInAndroid(IPEndPoint ipe)
        {
            Socket c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个Socket
            try
            {

                c.Connect(ipe);//连接到服务器


                byte[] pathByte = Encoding.UTF8.GetBytes(renamePath);
                byte[] nameByte = Encoding.UTF8.GetBytes(renameDestPath);
                c.Send(Instruction2bytes(RENAME, pathByte.Length, nameByte.Length, 0), 16, 0);
                c.Send(pathByte);
                c.Send(nameByte);
                byte[] recvBytes = new byte[4];
                c.Receive(recvBytes, 4, 0);
                int result = Bytes2Int(recvBytes);
                if (result != 0)
                {
                    if (result == 1)
                    {
                        MessageBox.Show("文件名重复了...重命名失败,刷新一下!!");
                    }
                    else if (result == 2)
                    {
                        MessageBox.Show("手机端出现奇怪的问题....重命名失败, 刷新一下!!");
                    }
                    else
                    {
                        MessageBox.Show("这个.....我也不知道重命名成功还是失败了...自己刷新看看!!..");
                    }
                }

            }
            catch (ArgumentNullException)
            {
                //Console.WriteLine("ArgumentNullException:{0}", e);

            }
            catch (SocketException ex)
            {
                dealException(ex.Message.ToString());
                //Console.WriteLine("SocketException:{0}", e);
            }
            catch (Exception ex)
            {
                dealException(ex.Message.ToString());
            }
            finally
            {
                if (c != null)
                {
                    c.Close();
                    c = null;
                }
            }
        }

        private void androidForAndroid(IPEndPoint ipe, string androidPath, string name)
        {
            Socket c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个Socket
            try
            {

                c.Connect(ipe);//连接到服务器

                byte[] pathByte = Encoding.UTF8.GetBytes(androidPath);
                byte[] nameByte = Encoding.UTF8.GetBytes(renamePath + name);
                if (cutFlag)
                {
                    c.Send(Instruction2bytes(CUT, pathByte.Length, nameByte.Length, 0), 16, 0);
                }
                else
                {
                    c.Send(Instruction2bytes(ADNROIDTOANDROID, pathByte.Length, nameByte.Length, 0), 16, 0);
                }

                c.Send(pathByte);
                c.Send(nameByte);
                //showCopyForm("手机内部复制当中,稍等........~~", 0, false, false);
                //loadingForm = new loading();
                //loadingForm.setText("手机内部复制当中,稍等........~~");
                //loadingForm.Show();

                MethodInvoker mi = new MethodInvoker(creatCopyingForm);
                BeginInvoke(mi);

                byte[] recvBytes = new byte[4];
                c.Receive(recvBytes, 4, 0);
                int result = Bytes2Int(recvBytes);
                if (result != 0)
                {
                    if (result == 1)
                    {
                        MessageBox.Show("文件名重复了...复制失败!");
                    }
                    else if (result == 2)
                    {
                        MessageBox.Show("手机端出现奇怪的问题....复制失败");
                    }
                    else
                    {
                        MessageBox.Show("这个.....我也不知道复制成功还是失败了.");
                    }
                }

            }
            catch (ArgumentNullException)
            {
                //Console.WriteLine("ArgumentNullException:{0}", e);

            }
            catch (Exception ex)
            {
                dealException(ex.Message.ToString());
            }
            finally
            {
                if (c != null)
                {
                    c.Close();
                    c = null;
                }
            }
        }

        private void deleteInAndroid(IPEndPoint ipe, string deletePath)
        {
            Socket c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个Socket
            try
            {

                c.Connect(ipe);//连接到服务器

                byte[] pathByte = Encoding.UTF8.GetBytes(deletePath);
                c.Send(Instruction2bytes(DELETE, pathByte.Length, 0, 0), 16, 0);

                c.Send(pathByte);
                showCopyForm("手机内部文件删除当中,稍等........~~", 0, false, false);
                byte[] recvBytes = new byte[4];
                c.Receive(recvBytes, 4, 0);
                int result = Bytes2Int(recvBytes);
                //if (result != 0)
                //{
                //    if (result == 1)
                //    {
                //        MessageBox.Show("文件名重复了...复制失败!");
                //    }
                //    else if (result == 2)
                //    {
                //        MessageBox.Show("手机端出现奇怪的问题....复制失败");
                //    }
                //    else
                //    {
                //        MessageBox.Show("这个.....我也不知道复制成功还是失败了.");
                //    }
                //}

            }
            catch (ArgumentNullException)
            {
                //Console.WriteLine("ArgumentNullException:{0}", e);

            }
            catch (Exception ex)
            {
                dealException(ex.Message.ToString());
            }
            finally
            {
                if (c != null)
                {
                    c.Close();
                    c = null;
                }
            }

        }
        private void newDirInAndroid(IPEndPoint ipe, string newPath)
        {
            Socket c = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个Socket
            try
            {

                c.Connect(ipe);//连接到服务器

                byte[] pathByte = Encoding.UTF8.GetBytes(newPath);
                c.Send(Instruction2bytes(NEW, pathByte.Length, 0, 0), 16, 0);

                c.Send(pathByte);
                //showCopyForm("手机内部文件删除当中,稍等........~~", 0, false, false);
                byte[] recvBytes = new byte[4];
                c.Receive(recvBytes, 4, 0);
                int result = Bytes2Int(recvBytes);
                if (result != 0)
                {
                    if (result == 1)
                    {
                        MessageBox.Show("文件名重复了...新建文件夹失败!");
                    }

                    else
                    {
                        MessageBox.Show("这个.....我也不知道新建文件夹成功还是失败了. 刷新试试看~~");
                    }
                }

            }
            catch (ArgumentNullException)
            {
                //Console.WriteLine("ArgumentNullException:{0}", e);

            }
            catch (Exception ex)
            {
                dealException(ex.Message.ToString());
            }
            finally
            {
                if (c != null)
                {
                    c.Close();
                    c = null;
                }
            }

        }
        //private void button2_Click(object sender, EventArgs e)
        //{
        //    ArrayList al = new ArrayList();
        //    String str = "abc";
        //    sendThread.Resume();
        //    //al.Add(al);
        //    //al.
        //}

        //private void SendString(Socket c, string str)
        //{
        //    byte[] strByte = Encoding.UTF8.GetBytes(androidPath);
        //}

        private string ReceiveStringStream(NetworkStream c)
        {
            byte[] sizeBytes = new byte[4];
            //c.Receive(sizeBytes, 4, 0);
            c.Read(sizeBytes, 0, 4);

            //Err.ErrorLog("./Logs/Log.txt", "sizeBytes --->" + sizeBytes.GetValue(0).ToString() + "--" + sizeBytes.GetValue(1).ToString() + "--" + sizeBytes.GetValue(2).ToString() + "--" + sizeBytes.GetValue(3).ToString());

            int size = Bytes2Int(sizeBytes);
            //Err.ErrorLog("./Logs/Log.txt", "size ------------------->" + size.ToString());
            string result = "";

            try
            {
                if (size > 1024)
                {
                    if (!alertFlag)
                    {
                        MessageBox.Show("哟....人品咁好啊,传输出错都比你遇到~  重新操作");
                        alertFlag = true;
                    }


                }
                else if (size != 0)
                {
                    //Err.ErrorLog("./Logs/Log.txt", "sizeBytes --->" + size);


                    byte[] stringBytes = new byte[size];
                    int bytes;
                    bytes = c.Read(stringBytes, 0, size);
                    result += Encoding.UTF8.GetString(stringBytes, 0, bytes);
                    //Err.ErrorLog("./Log.txt", "result --->" + result);
                    //Err.ErrorLog("./Logs/Log.txt", "result --->" + result);
                }
            }
            catch (OverflowException)
            {
                if (!alertFlag)
                {
                    MessageBox.Show("哟....人品咁好啊,传输出错都比你遇到~  重新操作");
                    alertFlag = true;
                }

            }

            //MessageBox.Show(size.ToString() + "-----" + result);
            return result;

        }

        private string ReceiveString(Socket c)
        {
            byte[] sizeBytes = new byte[4];
            c.Receive(sizeBytes, 4, 0);

            //Err.ErrorLog("./Logs/Log.txt", "sizeBytes --->" + sizeBytes.GetValue(0).ToString() + "--" + sizeBytes.GetValue(1).ToString() + "--" + sizeBytes.GetValue(2).ToString() + "--" + sizeBytes.GetValue(3).ToString());

            int size = Bytes2Int(sizeBytes);
            //Err.ErrorLog("./Logs/Log.txt", "size ------------------->" + size.ToString());
            string result = "";

            try
            {
                if (size > 1024)
                {
                    if (!alertFlag)
                    {
                        MessageBox.Show("哟....人品咁好啊,传输出错都比你遇到~  重新操作");
                        alertFlag = true;
                    }


                }
                else if (size != 0)
                {
                    //Err.ErrorLog("./Logs/Log.txt", "sizeBytes --->" + size);


                    byte[] stringBytes = new byte[size];
                    int bytes;
                    bytes = c.Receive(stringBytes, size, 0);
                    result += Encoding.UTF8.GetString(stringBytes, 0, bytes);

                    //Err.ErrorLog("./Logs/Log.txt", "result --->" + result);
                }
            }
            catch (OverflowException)
            {
                if (!alertFlag)
                {
                    MessageBox.Show("哟....人品咁好啊,传输出错都比你遇到~  重新操作");
                    alertFlag = true;
                }
            }

            //MessageBox.Show(size.ToString() + "-----" + result);
            return result;

        }

        private void showAndroidListView(string menuName, List<string> directoryNames, List<string> directoryTimes, List<string> fiNames, List<string> fiTimes, List<string> fiSizes)
        {
            System.EventArgs e = new MyProgressEvents(menuName, directoryNames, directoryTimes, fiNames, fiTimes, fiSizes);
            object[] pList = { this, e };
            BeginInvoke(new MyProgressEventsHandler(UpdateUI), pList);
        }

        private void showCopyForm(String name, int size, bool isClose, bool isPC)
        {
            System.EventArgs e = new copyEcents(name, size, isClose, isPC);
            object[] pList = { this, e };
            BeginInvoke(new copyEventsHandler(updateCopyForm), pList);
        }

        private delegate void MyProgressEventsHandler(object sender, MyProgressEvents e);
        private delegate void copyEventsHandler(object sender, copyEcents e);

        private void updateCopyForm(object sender, copyEcents e)
        {
            if (e.isClose)
            {
                if (copyForm != null)
                {
                    copyForm.Hide();

                }
                listViewForAndroid.Enabled = true;
                toolStripForAndroid.Enabled = true;
                cleanStringList();
                if (e.isPC)
                {
                    refreshPC();
                }
                else
                {
                    //refreshAndroid();
                }
                //if (cutFlag)
                //{
                //    refreshPC();
                //}
            }
            else
            {
                if (copyForm == null)
                {
                    copyForm = new copying();
                }
                copyForm.setText(e.copyName, e.count);
                copyForm.setProgress(e.count);
                copyForm.Show();
                listViewForAndroid.Enabled = false;
                toolStripForAndroid.Enabled = false;
            }
        }

        private void UpdateUI(object sender, MyProgressEvents e)
        {

            ToolStripSplitButton AndroidRootSplitButton = new ToolStripSplitButton();
            AndroidRootSplitButton.Text = e.splitButtonName;
            string frontPath = null;
            if (e.splitButtonName == "SD卡")
            {
                this.toolStripForAndroid.Items.Clear();
                frontPath = "";
                AndroidRootSplitButton.Tag = "0" + "?" + "";
                menuIndex = 0;
            }
            else
            {
                menuIndex++;
                frontPath = threadPath;
                AndroidRootSplitButton.Tag = menuIndex.ToString() + "?" + threadPath;
            }
            AndroidRootSplitButton.ButtonClick += new EventHandler(AndroidRootSplitButton_ButtonClick);
            //AndroidRootSplitButton.DropDownItemClicked += new ToolStripItemClickedEventHandler(PCRootSplitButton_DropDownItemClicked);
            this.toolStripForAndroid.Items.Add(AndroidRootSplitButton);

            listViewForAndroid.Items.Clear();
            this.listViewForAndroid.BeginUpdate();
            for (int i = 0; i < e.directoryNames.Count; i++)
            {
                ListViewItem lvi = new ListViewItem(new string[]{
                    e.directoryNames[i], e.directoryTimes[i], ""}, 1);
                lvi.Text = e.directoryNames[i];
                lvi.Tag = frontPath + "/" + e.directoryNames[i];
                listViewForAndroid.Items.Add(lvi);
            }
            for (int i = 0; i < e.fileNames.Count; i++)
            {
                ListViewItem lvi = new ListViewItem(new string[]{
                    e.fileNames[i], e.fileTimes[i], e.fileSizes[i], ""}, 2);
                lvi.Text = e.fileNames[i];
                lvi.Tag = frontPath + "/" + e.fileNames[i];
                listViewForAndroid.Items.Add(lvi);
            }
            this.listViewForAndroid.EndUpdate();

        }

        public static int Bytes2Int(byte[] byteVal)
        {
            int result = 0;
            for (int i = 0; i < byteVal.Length; i++)
            {
                int tmpVal = (byteVal[i] << (8 * (3 - i)));
                switch (i)
                {
                    case 0:
                        tmpVal = (int)(tmpVal & 0xFF000000);
                        break;
                    case 1:
                        tmpVal = (int)(tmpVal & 0x00FF0000);
                        break;
                    case 2:
                        tmpVal = (int)(tmpVal & 0x0000FF00);
                        break;
                    case 3:
                        tmpVal = (int)(tmpVal & 0x000000FF);
                        break;
                }
                result = result | tmpVal;
            }
            return result;
        }


        public static byte[] Instruction2bytes(int cmd, int pathSize, int nameSize, int fileSize)
        {
            byte[] result = new byte[16];
            result[0] = (byte)((cmd & 0xFF000000) >> 24);
            result[1] = (byte)((cmd & 0x00FF0000) >> 16);
            result[2] = (byte)((cmd & 0x0000FF00) >> 8);
            result[3] = (byte)((cmd & 0x000000FF));
            result[4] = (byte)((pathSize & 0xFF000000) >> 24);
            result[5] = (byte)((pathSize & 0x00FF0000) >> 16);
            result[6] = (byte)((pathSize & 0x0000FF00) >> 8);
            result[7] = (byte)((pathSize & 0x000000FF));
            result[8] = (byte)((nameSize & 0xFF000000) >> 24);
            result[9] = (byte)((nameSize & 0x00FF0000) >> 16);
            result[10] = (byte)((nameSize & 0x0000FF00) >> 8);
            result[11] = (byte)((nameSize & 0x000000FF));
            result[12] = (byte)((fileSize & 0xFF000000) >> 24);
            result[13] = (byte)((fileSize & 0x00FF0000) >> 16);
            result[14] = (byte)((fileSize & 0x0000FF00) >> 8);
            result[15] = (byte)((fileSize & 0x000000FF));
            return result;
        }

        private void listViewForAndroid_ItemActivate(object sender, EventArgs e)
        {
            if (listViewForAndroid.FocusedItem.ImageIndex == 1)
            {
                threadMenuName = listViewForAndroid.FocusedItem.Text;
                threadPath = listViewForAndroid.FocusedItem.Tag.ToString();
                //CreateLogFiles Err = new CreateLogFiles();
                //Err.ErrorLog("./Logs/Log.txt", "listViewForAndroid.FocusedItem.Tag.ToString()--->" + listViewForAndroid.FocusedItem.Tag.ToString());
                //sendCmd = SHOW;
                //sendThread.Resume();
                sendThread = new Thread(new ThreadStart(sendMess));
                sendCmd = SHOW;
                sendThread.IsBackground = true;
                sendThread.Start();
            }
            else
            {
                //MessageBox.Show("手机上的文件是不能直接打开滴.....");
                ListViewItem.ListViewSubItem lvs = listViewForAndroid.FocusedItem.SubItems[2];
                string size = lvs.Text.ToString();
                bool isSmall = false;
                if (size.Contains("MB"))
                {
                    string nums = size.Substring(0, size.IndexOf("MB") - 1);
                    float f = 100;
                    float.TryParse(nums, out f);
                    if (f < 5)
                    {
                        isSmall = true;
                    }
                }


                if (size.Contains("Bytes") || size.Contains("KB") || isSmall)
                {
                    copyInAndroid.Clear();
                    copyInAndroid.Add(listViewForAndroid.FocusedItem.Tag.ToString());
                    pastePCPath = ".\\temp";
                    openFlag = true;
                    cutFlag = false;
                    //sendCmd = PASTEFROMANDROID;
                    //sendThread.Resume();
                    sendThread = new Thread(new ThreadStart(sendMess));
                    sendCmd = PASTEFROMANDROID;
                    sendThread.IsBackground = true;
                    sendThread.Start();
                }
                else
                {
                    MessageBox.Show("手机上超过5M的文件复制过来再打开吧.....");
                }
            }
        }

        void AndroidRootSplitButton_ButtonClick(object sender, EventArgs e)
        {
            ToolStripSplitButton clickedButton = sender as ToolStripSplitButton;
            string tag = clickedButton.Tag.ToString();
            String[] splitStrings = new String[2];
            char[] separator = { '?' };
            splitStrings = tag.Split(separator);
            //MessageBox.Show(splitStrings[1]);
            int currentIndex = int.Parse(splitStrings[0]);
            menuIndex = currentIndex - 1;

            //CreateLogFiles Err = new CreateLogFiles();
            //Err.ErrorLog("./Logs/Log.txt", "items.count--->" + toolStripForAndroid.Items.Count.ToString() + "currentIndex--->" + currentIndex.ToString());


            for (int i = toolStripForAndroid.Items.Count - 1; i >= currentIndex; i--)
            {
                toolStripForAndroid.Items.RemoveAt(i);
            }



            threadMenuName = clickedButton.Text;
            if (threadMenuName == "SD卡")
            {
                threadPath = "";
            }
            else
            {
                threadPath = splitStrings[1];
            }

            //Err.ErrorLog("./Logs/Log.txt", "threadMenuName---->" + clickedButton.Text + "       threadPath---->" + threadPath);
            //sendCmd = SHOW;
            //sendThread.Resume();
            sendThread = new Thread(new ThreadStart(sendMess));
            sendCmd = SHOW;
            sendThread.IsBackground = true;
            sendThread.Start();
        }

        private void listViewForPC_MouseUp(object sender, MouseEventArgs e)
        {
            //if (e.Button == MouseButtons.Right)
            //{
            //    if (listViewForPC.SelectedItems.Count > 0)
            //    {
            //        //MessageBox.Show("click");

            //        Point po = listViewForPC.PointToScreen(new Point(e.X, e.Y));
            //        contextMenu.Show(po.X, po.Y);
            //    }
            //    //ListViewItem xy = listView1.GetItemAt(e.X, e.Y);
            //    //if (xy != null)
            //    //{
            //    //    Point point = this.PointToClient(listView1.PointToScreen(new Point(e.X, e.Y)));
            //    //    this.contextMenuStrip1.Show(this, point);
            //    //}
            //}
        }

        private void 复制ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            cutFlag = false;
            copyButtonClickInPC();
        }

        private void copyButtonClickInPC()
        {

            cleanStringList();

            foreach (ListViewItem lvi in listViewForPC.SelectedItems)
            {
                if (lvi.ImageIndex == 1)
                {
                    copyDirInPC.Add(lvi.Tag.ToString());
                }
                else
                {
                    copyFileInPC.Add(lvi.Tag.ToString());
                }
                //fileNames.Add(lvi.Text);  
            }
        }

        private void 复制ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            cutFlag = false;
            copyButtonClickInAndroid();
        }

        private void copyButtonClickInAndroid()
        {
            cleanStringList();
            foreach (ListViewItem lvi in listViewForAndroid.SelectedItems)
            {
                copyInAndroid.Add(lvi.Tag.ToString());
                //Err.ErrorLog("./Logs/Log.txt", "PC 粘贴CLICK" + lvi.Tag.ToString());
            }
        }


        private void 粘贴ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //Err.ErrorLog("./Logs/Log.txt", "PC 粘贴CLICK");
            if (copyDirInPC.Count != 0 || copyFileInPC.Count != 0 || copyInAndroid.Count != 0)
            {

                int index = toolStripForPC.Items.Count;
                if (copyingFlag)
                {
                    MessageBox.Show("唔支持同时粘贴哇 ");
                }
                else
                {
                    if (index == 1)
                    {
                        MessageBox.Show("玩野啊~ 宜个地方肯定不能用粘贴啦 ");
                    }
                    else
                    {
                        ToolStripSplitButton currentSplitButton = (ToolStripSplitButton)toolStripForPC.Items[index - 1];
                        string rootPathTemp = currentSplitButton.Tag.ToString();
                        string rootPath = rootPathTemp.Substring(rootPathTemp.IndexOf("?") + 1);

                        pastePCPath = rootPath;

                        copyingFlag = true;
                        if (copyInAndroid.Count != 0)
                        {
                            //sendCmd = PASTEFROMANDROID;
                            //sendThread.Resume();
                            sendThread = new Thread(new ThreadStart(sendMess));
                            sendCmd = PASTEFROMANDROID;
                            sendThread.IsBackground = true;
                            sendThread.Start();
                        }
                        if (copyDirInPC.Count != 0)
                        {
                            if (cutFlag)
                            {
                                if (copyDirInPC[0].Substring(0, 1) == pastePCPath.Substring(0, 1))
                                {
                                    foreach (string dirPath in copyDirInPC)
                                    {
                                        Directory.Move(dirPath, pastePCPath + dirPath.Substring(dirPath.LastIndexOf("\\")));
                                        refreshPC();
                                    }
                                }
                                else
                                {
                                    MessageBox.Show("顶 系唔同嘅盘符之间剪切....咁无聊嘅操作果断去自带的我的电脑做啦");
                                }

                            }
                            else
                            {
                                MessageBox.Show("喂喂....我个软件系用来手机同电脑通信架...唔系叫你系电脑入边自己玩复制啊");
                            }
                            copyingFlag = false;
                        }
                        if (copyFileInPC.Count != 0)
                        {
                            if (cutFlag)
                            {
                                if (copyFileInPC[0].Substring(0, 1) == pastePCPath.Substring(0, 1))
                                {
                                    foreach (string dirPath in copyFileInPC)
                                    {
                                        File.Move(dirPath, pastePCPath + dirPath.Substring(dirPath.LastIndexOf("\\")));
                                        refreshPC();
                                    }
                                }
                                else
                                {
                                    MessageBox.Show("顶 系唔同嘅盘符之间剪切....咁无聊嘅操作果断去自带的我的电脑做啦");
                                }

                            }
                            else
                            {
                                MessageBox.Show("喂喂....我个软件系用来手机同电脑通信架...唔系叫你系电脑入边自己玩复制啊");
                            }
                            copyingFlag = false;
                        }


                    }

                }
            }



        }

        private void 粘贴ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            ToolStripSplitButton currentSplitButton = (ToolStripSplitButton)toolStripForAndroid.Items[toolStripForAndroid.Items.Count - 1];
            string rootPathTemp = currentSplitButton.Tag.ToString();
            string rootPath = rootPathTemp.Substring(rootPathTemp.IndexOf("?") + 1);
            //Err.ErrorLog("./Logs/Log.txt", "rootPath --->" + rootPath);
            if (copyFileInPC.Count != 0 || copyDirInPC.Count != 0)
            {
                if (copyFileInPC.Count != 0)
                {
                    foreach (string filepath in copyFileInPC)
                    {
                        FileInfo file = new FileInfo(filepath);
                        filePaths.Add(filepath);
                        filePathsForAndroid.Add(rootPath);
                        fileNames.Add(file.Name);
                    }
                }
                if (copyDirInPC.Count != 0)
                {
                    foreach (string dirPath in copyDirInPC)
                    {
                        string androidpath = rootPath + "/" + dirPath.Substring(dirPath.LastIndexOf('\\') + 1);
                        //Err.ErrorLog("./Logs/Log.txt", "first androidpath --->" + androidpath);
                        addcopyDir(dirPath, androidpath);
                    }
                }
                //sendCmd = COPYTOANDROID;
                //sendThread.Resume();
                sendThread = new Thread(new ThreadStart(sendMess));
                sendCmd = COPYTOANDROID;
                sendThread.IsBackground = true;
                sendThread.Start();
            }
            if (copyInAndroid.Count != 0)
            {
                renamePath = rootPath;
                //sendCmd = ADNROIDTOANDROID;
                //sendThread.Resume();
                sendThread = new Thread(new ThreadStart(sendMess));
                sendCmd = ADNROIDTOANDROID;
                sendThread.IsBackground = true;
                sendThread.Start();
            }

        }

        private void addcopyDir(string dirPath, string androidPath)
        {
            DirectoryInfo dir = new DirectoryInfo(dirPath);
            DirectoryInfo[] subDirs = null;
            FileInfo[] subFiles = null;
            try
            {
                subDirs = dir.GetDirectories();
                subFiles = dir.GetFiles();
            }
            catch (UnauthorizedAccessException)
            {
                MessageBox.Show("没权限~");
            }
            if (subDirs != null)
            {
                foreach (DirectoryInfo subDir in subDirs)
                {
                    addcopyDir(subDir.FullName, androidPath + "/" + subDir.Name);
                }
            }
            if (subFiles != null)
            {
                foreach (FileInfo subFile in subFiles)
                {
                    filePaths.Add(subFile.FullName);
                    filePathsForAndroid.Add(androidPath);
                    fileNames.Add(subFile.Name);

                    //Err.ErrorLog("./Logs/Log.txt", "filePaths --->" + subFile.FullName + "       filePathsForAndroid --->" + androidPath + "       fileNames --->" + subFile.Name);
                }
            }


        }

        private void contextMenuForPC_Opening(object sender, CancelEventArgs e)
        {
            if (listViewForPC.SelectedItems.Count > 0)
            {
                abcToolStripMenuItem.Visible = true;
                剪切ToolStripMenuItem.Visible = true;
                复制ToolStripMenuItem.Visible = true;
                删除ToolStripMenuItem.Visible = true;
                重命名ToolStripMenuItem.Visible = true;
                toolStripSeparator2.Visible = true;

                粘贴ToolStripMenuItem.Visible = false;
                新建文件夹ToolStripMenuItem.Visible = false;
                查看ToolStripMenuItem.Visible = false;
                刷新ToolStripMenuItem.Visible = false;
                toolStripSeparator3.Visible = false;
            }
            else
            {

                abcToolStripMenuItem.Visible = false;
                剪切ToolStripMenuItem.Visible = false;
                复制ToolStripMenuItem.Visible = false;
                删除ToolStripMenuItem.Visible = false;
                重命名ToolStripMenuItem.Visible = false;
                toolStripSeparator2.Visible = false;

                粘贴ToolStripMenuItem.Visible = true;
                新建文件夹ToolStripMenuItem.Visible = true;
                查看ToolStripMenuItem.Visible = true;
                刷新ToolStripMenuItem.Visible = true;
                toolStripSeparator3.Visible = true;
            }
        }

        private void 图标ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            listViewForAndroid.View = View.LargeIcon;
            listViewForPC.View = View.LargeIcon;
        }


        private void 详细ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            listViewForAndroid.View = View.Details;
            listViewForPC.View = View.Details;
        }

        private void contextMenuForAndroid_Opening(object sender, CancelEventArgs e)
        {
            if (listViewForAndroid.SelectedItems.Count > 0)
            {
                剪切ToolStripMenuItem1.Visible = true;
                复制ToolStripMenuItem1.Visible = true;
                删除ToolStripMenuItem1.Visible = true;
                重命名ToolStripMenuItem1.Visible = true;

                粘贴ToolStripMenuItem1.Visible = false;
                新建文件夹ToolStripMenuItem1.Visible = false;
                查看ToolStripMenuItem1.Visible = false;
                刷新ToolStripMenuItem1.Visible = false;
                toolStripSeparator1.Visible = false;
            }
            else
            {

                剪切ToolStripMenuItem1.Visible = false;
                复制ToolStripMenuItem1.Visible = false;
                删除ToolStripMenuItem1.Visible = false;
                重命名ToolStripMenuItem1.Visible = false;

                粘贴ToolStripMenuItem1.Visible = true;
                新建文件夹ToolStripMenuItem1.Visible = true;
                查看ToolStripMenuItem1.Visible = true;
                刷新ToolStripMenuItem1.Visible = true;
                toolStripSeparator1.Visible = true;
            }
        }

        private void 刷新ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            alertFlag = false;
            refreshPC();
        }

        private void 刷新ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            alertFlag = false;
            refreshAndroid();
        }

        private void refreshPC()
        {
            ToolStripSplitButton currentSplitButton = (ToolStripSplitButton)toolStripForPC.Items[toolStripForPC.Items.Count - 1];
            if (toolStripForPC.Items.Count - 1 != 0)
            {
                string rootPathTemp = currentSplitButton.Tag.ToString();
                string rootPath = rootPathTemp.Substring(rootPathTemp.IndexOf("?") + 1);
                showPCListView(rootPath, currentSplitButton.Text, false);
            }

        }

        private void setRefreshPath()
        {
            int currentIndex = toolStripForAndroid.Items.Count - 1;
            ToolStripSplitButton currentSplitButton = (ToolStripSplitButton)toolStripForAndroid.Items[currentIndex];
            string rootPathTemp = currentSplitButton.Tag.ToString();
            string rootPath = rootPathTemp.Substring(rootPathTemp.IndexOf("?") + 1);
            threadMenuName = currentSplitButton.Text;
            if (threadMenuName == "SD卡")
            {
                threadPath = "";
            }
            else
            {
                threadPath = rootPath;
            }

            toolStripForAndroid.Items.RemoveAt(currentIndex);
            menuIndex--;
        }

        private void refreshAndroid()
        {
            setRefreshPath();
            //sendCmd = SHOW;
            //Err.ErrorLog("./Logs/Log.txt", "isLoadingFlag  before refresh resume--->" + this.sendThread.ThreadState.ToString());
            //sendThread.Resume();
            sendThread = new Thread(new ThreadStart(sendMess));
            sendCmd = SHOW;
            sendThread.IsBackground = true;
            sendThread.Start();
        }

        private void 重命名ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            listViewForPC.LabelEdit = true;
            listViewForPC.FocusedItem.BeginEdit();
            renameItem = listViewForPC.FocusedItem;
            isRename = true;
        }

        private void 重命名ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            listViewForAndroid.LabelEdit = true;
            listViewForAndroid.FocusedItem.BeginEdit();
            renameItem = listViewForAndroid.FocusedItem;
            isRename = true;
        }

        private void listViewForPC_AfterLabelEdit(object sender, LabelEditEventArgs e)
        {


            char[] anyOf = { '\\', '/', ':', '*', '?', '\"', '<', '>' };
            if (e.Label != null)
            {
                if (e.Label.ToString().IndexOfAny(anyOf) == -1)
                {

                    string firstPath = renameItem.Tag.ToString();
                    string root = firstPath.Substring(0, firstPath.LastIndexOf("\\") + 1);

                    //MessageBox.Show("firstPath--->" + firstPath + "   root---?" + root);

                    if (renameItem.ImageIndex == 0)
                    {
                        MessageBox.Show("玩野啊~ 重命名盘符系唔得架");
                    }
                    else if (renameItem.ImageIndex == 1)
                    {
                        Directory.Move(firstPath, root + e.Label.ToString());
                        renameItem.Tag = root + e.Label.ToString();
                    }
                    else
                    {
                        File.Move(firstPath, root + e.Label.ToString());
                        renameItem.Tag = root + e.Label.ToString();
                    }


                }
                else
                {
                    MessageBox.Show("  文件名不能包含下列任何字符: \\, /, :, *, ?, \", <, >");
                    listViewForPC.FocusedItem.BeginEdit();

                }
            }

        }

        private void listViewForAndroid_AfterLabelEdit(object sender, LabelEditEventArgs e)
        {
            //MessageBox.Show(e.Label.ToString());



            char[] anyOf = { '\\', '/', ':', '*', '?', '\"', '<', '>' };

            if (e.Label.ToString().IndexOfAny(anyOf) == -1)
            {
                if (isRename)
                {
                    renamePath = renameItem.Tag.ToString();
                    string root = renamePath.Substring(0, renamePath.LastIndexOf("/") + 1);
                    renameDestPath = root + e.Label.ToString();
                    renameItem.Tag = renameDestPath;
                    //MessageBox.Show("renamePath--->" + renamePath + "   renameDestPath" + renameDestPath);
                    //sendCmd = RENAME;
                    //sendThread.Resume();
                    sendThread = new Thread(new ThreadStart(sendMess));
                    sendCmd = RENAME;
                    sendThread.IsBackground = true;
                    sendThread.Start();
                }
                else
                {
                    int currentIndex = toolStripForAndroid.Items.Count - 1;
                    ToolStripSplitButton currentSplitButton = (ToolStripSplitButton)toolStripForAndroid.Items[currentIndex];
                    string rootPathTemp = currentSplitButton.Tag.ToString();
                    string rootPath = rootPathTemp.Substring(rootPathTemp.IndexOf("?") + 1);
                    renameItem.Tag = rootPath + "/" + e.Label.ToString();
                    renamePath = rootPath + "/" + e.Label.ToString();
                    //sendCmd = NEW;
                    //sendThread.Resume();
                    sendThread = new Thread(new ThreadStart(sendMess));
                    sendCmd = NEW;
                    sendThread.IsBackground = true;
                    sendThread.Start();
                }

            }
            else
            {
                MessageBox.Show("  文件名不能包含下列任何字符: \\, /, :, *, ?, \", <, >");
                listViewForAndroid.FocusedItem.BeginEdit();
            }
        }

        private void 剪切ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            cutFlag = true;
            copyButtonClickInPC();
        }

        private void 剪切ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            cutFlag = true;
            copyButtonClickInAndroid();
        }

        private void 删除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (showAlertDialog("是否要删除文件,此删除操作不会放入回收站..."))
            {
                foreach (ListViewItem lvi in listViewForPC.SelectedItems)
                {
                    if (lvi.ImageIndex == 0)
                    {
                        MessageBox.Show("玩野啊...磁盘点删除");
                    }
                    else if (lvi.ImageIndex == 1)
                    {
                        DeleteFolder(lvi.Tag.ToString());
                    }
                    else
                    {
                        DeleteFile(lvi.Tag.ToString());
                    }
                }
                refreshPC();
            }
        }

        private void 删除ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (showAlertDialog("是否要删除手机上文件,此删除操作不会放入回收站..."))
            {
                deleteList.Clear();
                foreach (ListViewItem lvi in listViewForAndroid.SelectedItems)
                {
                    deleteList.Add(lvi.Tag.ToString());
                }
                //sendCmd = DELETE;
                //sendThread.Resume();
                sendThread = new Thread(new ThreadStart(sendMess));
                sendCmd = DELETE;
                sendThread.IsBackground = true;
                sendThread.Start();
            }
        }

        private bool showAlertDialog(string text)
        {
            Boolean result = false;
            DialogResult MsgBoxResult;//设置对话框的返回值

            MsgBoxResult = MessageBox.Show(text,//对话框的显示内容

            "提示",//对话框的标题

            MessageBoxButtons.YesNo,//定义对话框的按钮，这里定义了YSE和NO两个按钮

            MessageBoxIcon.Exclamation,//定义对话框内的图表式样，这里是一个黄色三角型内加一个感叹号

            MessageBoxDefaultButton.Button2);//定义对话框的按钮式样

            if (MsgBoxResult == DialogResult.Yes)//如果对话框的返回值是YES（按"Y"按钮）
            {
                result = true;

            }
            return result;
        }

        public void DeleteFolder(string strDirPath)
        {
            if (Directory.Exists(strDirPath))           //如果存在这个文件夹，执行删除操作
            {
                foreach (string d in Directory.GetFileSystemEntries(strDirPath))
                {
                    if (File.Exists(d))
                        File.Delete(d);                 //直接删除其中的文件
                    else
                        DeleteFolder(d);                //递归删除子文件夹
                }
                Directory.Delete(strDirPath, true);     //删除已空文件夹
            }
        }

        public void DeleteFile(string strFilePath)
        {
            if (File.Exists(strFilePath))
            {
                File.Delete(strFilePath);
            }
        }


        //private void 剪切ToolStripMenuItem_Click(object sender, EventArgs e)
        //{
        //    MessageBox.Show("click ");
        //    cutFlag = true;
        //    copyButtonClickInPC();
        //}

        //private void 打开ToolStripMenuItem_Click(object sender, EventArgs e)
        //{
        //    cutFlag = true;
        //    copyButtonClickInAndroid();
        //}
        private void creatCopyingForm()
        {
            loadingForm = new loading();
            loadingForm.setText("手机内部复制当中,稍等........~~");
            loadingForm.Show();
        }

        private void closeLoading()
        {
            if (loadingForm != null)
            {
                loadingForm.Close();
            }
            listViewForAndroid.Enabled = true;
            if (timeOutFlag)
            {
                //MessageBox.Show("连接手机超时...~请确认手机端打开程序和输入正确的IP");
                panelLogin.Visible = true;
                //sendCmd = STOP;
                timeOutFlag = false;
                //sendThread.Resume();

            }
        }

        private void connect1_Click(object sender, EventArgs e)
        {
            connectAndroid();

        }
        private void connectAndroid()
        {
            host = textBox1.Text;
            if (IPCheck(host))
            {
                if (!xmlOperation.isIPExit(host))
                {
                    xmlOperation.writeIP(host);
                }
                initAndroidListView();
                panelLogin.Visible = false;
                loadingForm = new loading();
                loadingForm.Show();
                listViewForAndroid.Enabled = false;
            }
            else
            {
                DialogResult MsgBoxResult;//设置对话框的返回值
                showIPWrongAlert = true;
                MsgBoxResult = MessageBox.Show("非法IP");

                if (MsgBoxResult == DialogResult.OK)//如果对话框的返回值是YES（按"Y"按钮）
                {
                    showIPWrongAlert = false;
                }            
            }
        }

        private bool IPCheck(string IP)
        {
            string num = "(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)";
            return Regex.IsMatch(IP, ("^" + num + "\\." + num + "\\." + num + "\\." + num + "$"));
        }

        private void 名称ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            arrangeType = TYPE_NAME;
            refreshAndroid();
        }

        private void 修改时间ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            arrangeType = TYPE_MODIFIED_DATE_DOWN;
            refreshAndroid();
        }

        private void 大小ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            arrangeType = TYPE_SIZE_DOWN;
            refreshAndroid();
        }

        private void 文件夹ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int currentIndex = toolStripForPC.Items.Count - 1;
            ToolStripSplitButton currentSplitButton = (ToolStripSplitButton)toolStripForPC.Items[currentIndex];
            string rootPathTemp = currentSplitButton.Tag.ToString();
            string rootPath = rootPathTemp.Substring(rootPathTemp.IndexOf("?") + 1);
            if (currentIndex == 0)
            {
                MessageBox.Show("依度肯定唔可以新建文件夹啦");
            }
            else
            {
                string path = rootPath + "\\" + "新建文件夹~";
                Directory.CreateDirectory(path);
                ListViewItem lvi = new ListViewItem(new string[]{
                    "新建文件夹~","", ""}, 1);
                lvi.Tag = path;
                renameItem = lvi;
                listViewForPC.Items.Add(lvi);
                listViewForPC.LabelEdit = true;
                lvi.BeginEdit();
                isRename = false;
            }
        }

        private void 文件夹ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            ListViewItem lvi = new ListViewItem(new string[]{
                    "","", ""}, 1);
            renameItem = lvi;
            listViewForAndroid.Items.Add(lvi);
            listViewForAndroid.LabelEdit = true;
            lvi.BeginEdit();
            isRename = false;
        }


        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter && !showIPWrongAlert)
            {
                connectAndroid();
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (checkBox1.Checked)
            {
                xmlOperation.writeConfig(CONFIG_REMEMBER_FLAG, "true");
                xmlOperation.writeConfig(CONFIG_IP,textBox1.Text);
            }
            else
            {
                xmlOperation.writeConfig(CONFIG_REMEMBER_FLAG, "false");
            }
            xmlOperation.writeConfig(CONFIG_WIDTH,(this.Size.Width - 16).ToString());
            xmlOperation.writeConfig(CONFIG_HEIGHT, (this.Size.Height - 38).ToString());
            xmlOperation.writeConfig(CONFIG_VIEW, listViewForPC.View.ToString());
            xmlOperation.writeConfig(CONFIG_COLUMN_NAME_WIDTH, listViewForPC.Columns[0].Width.ToString());
            xmlOperation.writeConfig(CONFIG_COLUMN_TIME_WIDTH, listViewForPC.Columns[1].Width.ToString());
            xmlOperation.writeConfig(CONFIG_COLUMN_SIZE_WIDTH, listViewForPC.Columns[2].Width.ToString());
        }

        private void dealException(string msg)
        {
            if (isConnectFlag)
            {
                MessageBox.Show("连接手机超时...~请确认手机端打开程序和输入正确的IP");
            }
            else
            {
                MessageBox.Show(msg + ",请检查无线网络环境,手机是否打开应用~");
            }
            
            sendThread.Abort();
        }
        //private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        //{
        //    MessageBox.Show(e.KeyChar.ToString());
        //}

        //private RegistryKey OpenRegistryPath(RegistryKey root, string s)
        //{

        //    s = s.Remove(0, 1) + @"/";

        //    while (s.IndexOf(@"/") != -1)
        //    {

        //        root = root.OpenSubKey(s.Substring(0, s.IndexOf(@"/")));

        //        s = s.Remove(0, s.IndexOf(@"/") + 1);

        //    }

        //    return root;
        

        //}

    }

    public class copyEcents : EventArgs
    {
        public string copyName;
        public int count;
        public bool isClose;
        public bool isPC;

        public copyEcents(string name, int size, bool close, bool pc)
        {
            copyName = name;
            count = size;
            isClose = close;
            isPC = pc;
        }
    }

    public class MyProgressEvents : EventArgs
    {

        public List<string> directoryNames;
        public List<string> directoryTimes;
        public List<string> fileNames;
        public List<string> fileSizes;
        public List<string> fileTimes;
        public string splitButtonName;
        public MyProgressEvents(string splitBtName, List<string> dirNames, List<string> dirTimes, List<string> fiNames, List<string> fiTimes, List<string> fiSizes)
        {
            splitButtonName = splitBtName;
            directoryNames = dirNames;
            directoryTimes = dirTimes;
            fileNames = fiNames;
            fileSizes = fiSizes;
            fileTimes = fiTimes;
        }
    }

    //用于获得系统图标
    [StructLayout(LayoutKind.Sequential)]
    public struct SHFILEINFO
    {
        public IntPtr hIcon;
        public IntPtr iIcon;
        public uint dwAttributes;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
        public string szDisplayName;
        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
        public string szTypeName;
    }

    class Win32
    {
        public const uint SHGFI_ICON = 0x100;
        public const uint SHGFI_LARGEICON = 0x0; // 'Large icon
        public const uint SHGFI_SMALLICON = 0x1; // 'Small icon
        [DllImport("shell32.dll")]
        public static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, uint cbSizeFileInfo, uint uFlags);
    }





    //用于Log 
    public class CreateLogFiles
    {
        private string sLogFormat;
        private string sErrorTime;

        public CreateLogFiles()
        {
            //sLogFormat used to create log files format :
            // dd/mm/yyyy hh:mm:ss AM/PM ==> Log Message
            sLogFormat = DateTime.Now.ToShortDateString().ToString() + " " + DateTime.Now.ToLongTimeString().ToString() + " ==> ";

            //this variable used to create log filename format "
            //for example filename : ErrorLogYYYYMMDD
            string sYear = DateTime.Now.Year.ToString();
            string sMonth = DateTime.Now.Month.ToString();
            string sDay = DateTime.Now.Day.ToString();
            sErrorTime = sYear + sMonth + sDay;
        }

        public void ErrorLog(string sPathName, string sErrMsg)
        {
            StreamWriter sw = new StreamWriter(sPathName, true);
            sw.WriteLine(sLogFormat + sErrMsg);
            sw.Flush();
            sw.Close();
        }
    }
}
